package com.zjj.disk.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zjj.disk.pojo.Dictionary;
import com.zjj.disk.service.DictionaryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController // 标记为Spring的Controller
@RequestMapping("/api/dictionary") // API路径前缀
public class DictionaryController {

    @Autowired
    private DictionaryService dictionaryService; // 注入DictionaryService


    /**
     * 根据ID获取字典项
     *
     * @param id 字典项ID
     * @return 字典项
     */
    @GetMapping("/{id}")
    public Dictionary getDictionaryById(@PathVariable Long id) {
        return dictionaryService.getById(id); // 根据ID获取字典项
    }


    /**
     * 添加父类
     *
     * @param parent 父类对象
     * @return 添加后的父类对象
     */
    @PostMapping("/parent")
    public Dictionary addParent(@RequestBody Dictionary parent) {
        return dictionaryService.addParent(parent); // 添加父类
    }

    /**
     * 添加子类
     *
     * @param child      子类对象
     * @param parentCode 父类编码
     * @return 添加后的子类对象
     */
    @PostMapping("/child")
    public Dictionary addChild(@RequestBody Dictionary child, @RequestParam String parentCode) {
        return dictionaryService.addChild(child, parentCode); // 添加子类
    }

    /**
     * 删除字典项
     *
     * @param id 要删除的字典项ID
     */
    @DeleteMapping("/{id}")
    public void deleteDictionary(@PathVariable Long id) {
        dictionaryService.deleteDictionary(id); // 删除字典项
    }

    /**
     * 根据父类编码查询字典项，支持分页
     *
     * @param parentCode 父类编码，如果为 null 则查询所有父类
     * @param currentPage    当前页码
     * @param pageSize       每页大小
     * @return 分页结果
     */
    @GetMapping("/by-parent-code")
    public IPage<Dictionary> listByParentCode(
            @RequestParam(required = false) String parentCode,
            @RequestParam(defaultValue = "1") int currentPage,
            @RequestParam(defaultValue = "10") int pageSize) {
        Page<Dictionary> page = new Page<>(currentPage, pageSize);
        return dictionaryService.listByParentCode(parentCode, page); // 根据父类编码查询字典项
    }

    @GetMapping("/dictionaries")
    public List<Dictionary> getDictionariesByParentCode(@RequestParam String parentCode) {
        return dictionaryService.getByParentCode(parentCode);
    }
}
